define(["angularAMD"], function (angularAMD) {
    angularAMD.service('B0235Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog',
        function($rootScope, $filter, $translate, config, $MMWService, $mdDialog){
            this.init = function (machineList, type,parent,feedback) {
                var OnWorkInfolist = []; //人员清单
                var tmpOnWorkInfo = {};//人员上工原因
                var need_work_reason = (config.cache.sys_parameter.EmployeeWorkReason == '1' || config.cache.sys_parameter.EmployeeWorkReason == '3'); //上工是否需輸入原因
                var errormsg = ""; //人员技能检核报错信息
                var errormsgfinal = "";

                function beforeEmpWorkSet(dialog, callback) {
                    if (need_work_reason && !dialog.tmpOnWorkInfo.reason_no) {
                        loadEmpWorkReason('', function (selectItem) {
                            dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                            dialog.tmpOnWorkInfo.reason_name = selectItem.page_name;
                            if (callback)
                                callback();
                        });
                    } else {
                        if (callback)
                            callback();
                    }
                }
                // 人員原因基本資料取得
                function loadEmpWorkReason(reason_no, callback) {
                    $MMWService.pageNumberInfoGet({
                        page_mode: '35',
                        query_condition_info: [
                            { column_name: 'REASONTYPE', query_mode: '0', value: '0', merge_condition_model: 'AND' },
                            { column_name: 'ISSUESTATE', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                        ]
                    }, function (items) {
                        if (items && items.length > 0) {
                            $rootScope.showSelect({
                                label: function (item) {
                                    return item.page_name + '(' + item.page_no + ')';
                                },
                                title: $filter('translate')('B0235.plz_select_reason'),
                                code: 'page_no',
                                selectCode: reason_no || '',
                                list: items,
                                confirm: function (selectItem, radio_dialog) {
                                    radio_dialog.hide();
                                    if (callback)
                                        callback(selectItem);
                                }
                            });
                        } else {
                            $rootScope.showAlert($filter('translate')('B0235.showAlert.column6'));
                        }
                    });
                }

                function addWorkItem(dialog, machine, employeewrokset) {
                    var msg = '';
                    
                    if (need_work_reason && !dialog.tmpOnWorkInfo.reason_no) {
                        msg += $filter('translate')('B0235.showAlert.column5') + "<br>";
                    }

                    if (msg == '') {
                        dialog.OnWorkInfo_detail.forEach(function (item) {
                            employeewrokset.push({
                                machine_no: machine.machine_no,
                                machine_name: machine.machine_name,
                                employee_no: item.user_no,
                                parameter_value: item.parameter_value == "" ? 0 : item.parameter_value,
                                work_mode: 'U',
                                work_datetime: new Date(),
                                reason_no: tmpOnWorkInfo.reason_no || ''
                            });
                        })
                     
                    }
                    return msg;
                }
                //上工
                function empWorkSet(dialog) {
                    var msg = '';
                    var content = {
                        employeewrokset: []
                    };

                    machineList.forEach(function (machine) {
                        msg += addWorkItem(dialog, machine, content.employeewrokset);
                    });

                    if (msg == '') {
                         if (content.employeewrokset.length > 0) {
                            employee_wrok_set_Imp(dialog, content);
                        } else {
                            $rootScope.showToast($filter('translate')('B0235.msg.user_list_empty'));
                        }
                    } else {
                        $rootScope.showAlert(msg);
                    }
                }

           
                // 檢查是否有設定技能
                function checkNeedInspetSkill(machine,type,feedback,secondfeedback) {
                    var page_mode = '';
                    var query_condition_info = [];

                    if (type === 0) {
                        page_mode = '40-1'; //設備設定技能取得
                        query_condition_info = [
                            { column_name: 't.EQUIPMENTNO', query_mode: '0', value: machine.machine_no, merge_condition_model: 'AND' }
                        ];
                    } else {
                        page_mode = '40-2'; //工位設定技能取得
                        query_condition_info = [
                            { column_name: 't.PDLINENO', query_mode: '0', value: '', merge_condition_model: 'AND' },
                            { column_name: 't.POSITIONNO', query_mode: '0', value: '', merge_condition_model: 'AND' }
                        ];
                    }

                    $MMWService.pageNumberInfoGet({
                        page_mode: page_mode,
                        query_condition_info: query_condition_info
                    }, function (items) {
                        if (items && items.length > 0) {
                            // 有設定技能，執行技能檢驗邏輯
                            if (feedback)
                                feedback();
                        } else {
                            // 不需檢驗人員技能，繼續執行上工逻辑
                            if (secondfeedback)
                                secondfeedback();
                        }
                    });
                }

               

                // 人員技能檢驗資訊取得
                function userSkillInspectInfoGet(content, machine, feedback) {
                    $MMWService.sendToSMESServer({
                        uri: 'tcSMES_skill.clsSMES.required_skills_info_get',
                        content: content,
                        success: function (data) {
                            if (data.error_msg && data.msg != "") {
                                var msglist = data.error_msg.split(",");
                                msglist.forEach(function (item) {
                                    var detail = item.split("-");
                                   errormsg = errormsg + detail[0] + $filter('translate')('B0235.showAlert.column7') + machine.machine_name + $filter('translate')('B0235.showAlert.column8') + detail[1] + $filter('translate')('B0235.showAlert.column9');
                                });
                            }
                            if (feedback)
                                feedback();

                        }
                    });
                }

                // 人員技能檢驗
                function inspectUserSkill(inspectInfo,dialog, feedback) {
                    if (inspectInfo && inspectInfo.length > 0) {
                        var machineInfo = inspectInfo.shift();
                        var typevalue = "";
                        var userlist = [];
                        if (parent == 'B0214' || parent == 'B0215' || parent == 'mobile_home') {
                            typevalue = 0;   // 0: 機台
                        } else if (parent == 'E01') {
                            typevalue = 1;   // 1: 工位
                        }
                        dialog.OnWorkInfo_detail.forEach(function (user) {
                            userlist.push(user.user_no);
                        });
                        var content = {
                            user_no_list: userlist,
                            type: typevalue  // 0: 機台, 1: 工位
                        };
                        if (typevalue == 0) {  // 機台查詢條件 = 機台編號
                            content.id = machineInfo.machine_no;
                        } else if (typevalue == 1) {    // 工位機查詢條件 = 工位機編號+區域編號+作業站編號
                            content.id = machineInfo.machine_no;
                            content.parameter1 = '',
                            content.parameter2 = '';
                        }

                        if (machineInfo && parent != 'B0201') { //生產線作業平台不支援技能檢驗
                            checkNeedInspetSkill(machineInfo, typevalue, function () {
                                userSkillInspectInfoGet(content,machineInfo, function () {
                                    inspectUserSkill(inspectInfo, dialog,feedback);
                                });
                            }, function () {
                                inspectUserSkill(inspectInfo, dialog, feedback);
                            });
                        } else {
                            if (feedback)
                                feedback();
                        }
                    } else {
                        if (feedback)
                            feedback();
                    }
                }
           
                function employee_wrok_set_Imp(dialog, content) {
                    var tempmachinelist = JSON.parse(JSON.stringify(machineList));
                    inspectUserSkill(tempmachinelist, dialog, function () {
					     if (errormsg != "")
					     {
					         errormsgfinal = errormsg.substring(0, errormsg.length - 1);
					         $rootScope.showAlert(errormsgfinal);
					     }
					     else {
					         employee_wrok_set(dialog, content);
					     }
					 });
                }


                function employee_wrok_set(dialog, content) {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.usr_report_group_process',
                        content: content,
                        success: function (data) {
                            $rootScope.showToast($filter('translate')('B0235.showAlert.column1')); 
							dialog.back();
                            if (feedback)
                                feedback();
                        }
                    });
                }

                $mdDialog.dialog(
                    'module/moduleB/program/B02/B0235/B0235.html',
                    function(dialog){
                        return {
                            css_url: 'module/moduleB/program/B02/B0235/B0235.css',
                            machine_list : machineList,
                            //machine_no: machineList[0].machine_no,  //設備
                            tmpUser_no: '',
                            checkedgroup: true, //预设为打勾
                            OnWorkInfo_detail: OnWorkInfolist,
                            need_work_reason: need_work_reason,
                            tmpOnWorkInfo: tmpOnWorkInfo,
                            group_user_list:[],
                            beforeShown: function () {
                                machineList.forEach(function (item) {
                                    item.employee_work_detail.forEach(function (workitem) {										
                                        var min_parameter_value = 0;
                                        var tempitem = $filter('filter')(OnWorkInfolist, { user_no: workitem.employee_no }, true);
                                        if (tempitem && tempitem.length > 0) {
                                            if (tempitem[0].parameter_value >= item.parameter_value) {
                                                min_parameter_value = item.parameter_value;
                                            }
                                            else {
                                                min_parameter_value = tempitem[0].parameter_value;
                                            }
                                            OnWorkInfolist.forEach(function (detail) {
                                                if (detail.user_no == tempitem[0].user_no) {
                                                    detail.parameter_value = min_parameter_value;
                                                }
                                            })
                                        }
                                        else
                                        {
                                            var tmpUser = {
                                                user_no: workitem.employee_no,
                                                user_name: workitem.employee_name,
                                                parameter_value: workitem.parameter_value
                                            };
                                            OnWorkInfolist.push(tmpUser);
                                        }
                                    })
									 if(item.CategoryLeader && item.CategoryLeader.length>0)
									 {
										 for(var i=0;i<item.CategoryLeader.length;i++){
											  if(dialog.group_user_list.indexOf(item.CategoryLeader[i]) <= -1)
											  {
												   dialog.group_user_list.push(item.CategoryLeader[i]);
											  }
										 }
									 }   
                                });
                                try{
                                    document.getElementById('tmpEmp_no').focus();
                                } catch(e){console.error(e);}
                            },
                            groupCheck: function () {
                                dialog.checkedgroup = !dialog.checkedgroup
                            },
                            deleteEmployee:function(index,item){
                                dialog.OnWorkInfo_detail.splice(index, 1);
                            },
                            searchUser: function (event) {
                                if (!event || event.keyCode == 13) {
                                    if (dialog.tmpUser_no != '') {
                                        if (dialog.checkedgroup)
                                        {
                                            var content = {
                                                type: "group",
                                                user_no: dialog.tmpUser_no     
                                            };
                                        }
                                        else {
                                            var content = {
                                                type: "user",
                                                user_no: dialog.tmpUser_no
                                            };
                                        }
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_WIP.usr_report_group_get',
                                            content: content,
                                            success: function (data) {
												if (data.group_user_list && data.group_user_list.length>0) {
													 for(var i=0;i<data.group_user_list.length;i++){
														  if(dialog.group_user_list.indexOf(data.group_user_list[i]) <= -1)
														  {
															   dialog.group_user_list.push(data.group_user_list[i]);
														  }
													 }
												}   
                                                dialog.addUser(data.report_group_detail);
                                            },
                                            error: function (data) {
                                                $rootScope.showAlert(data.Message, function () {
                                                    document.getElementById('tmpEmp_no').focus();
                                                });
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0235.msg.input_labor_empty'), function () {
                                            document.getElementById('tmpEmp_no').focus();
                                        });
                                    }
                                }
                            },
                            addUser: function (data) {
                                if (dialog.checkedgroup) { 
                                    if(data && data.length>0)
                                    {
                                        if(data.length==1)
                                        {
                                            data[0].user_detail.forEach(function (item) {
                                                var min_parameter_value=0;
                                                var temp = $filter('filter')(dialog.OnWorkInfo_detail,{user_no:item.user_no}, true);
                                                if(temp && temp.length>0){
                                                    if(temp[0].parameter_value>=item.parameter_value)
                                                    {
                                                        min_parameter_value=item.parameter_value;
                                                    }
                                                    else
                                                    {
                                                        min_parameter_value = temp[0].parameter_value;
                                                    }
                                                    dialog.OnWorkInfo_detail.forEach(function (detail) {
                                                        if (detail.user_no == temp[0].user_no) {
                                                            detail.parameter_value = min_parameter_value;
                                                        }
                                                    })
                                                }
                                                else
                                                {
                                                    var tmpUser = {
                                                        user_no: item.user_no,
                                                        user_name: item.user_name,
                                                        parameter_value: item.parameter_value
                                                    };
                                                    dialog.OnWorkInfo_detail.push(tmpUser);
                                                }
                                            })
                                        }
                                        else
                                        {
                                            $rootScope.showSelect({
                                                label: 'category',
                                                code: 'category',
                                                //selectCode: item.responseprocess,
                                                list: data,
                                                confirm: function (detail, radioDialog) {
                                                    radioDialog.hide();
                                                    detail.user_detail.forEach(function (item) {
                                                        var min_parameter_value = 0;
                                                        var temp = $filter('filter')(dialog.OnWorkInfo_detail, { user_no: item.user_no }, true);
                                                        if (temp && temp.length > 0) {
                                                            if (temp[0].parameter_value >= item.parameter_value) {
                                                                min_parameter_value = item.parameter_value;
                                                            }
                                                            else {
                                                                min_parameter_value = temp[0].parameter_value;
                                                            }
                                                            dialog.OnWorkInfo_detail.forEach(function (detail) {
                                                                if (detail.user_no == temp[0].user_no) {
                                                                    detail.parameter_value = min_parameter_value;
                                                                }
                                                            })
                                                        }
                                                        else {
                                                            var tmpUser = {
                                                                user_no: item.user_no,
                                                                user_name: item.user_name,
                                                                parameter_value: item.parameter_value
                                                            };
                                                            dialog.OnWorkInfo_detail.push(tmpUser);
                                                        }
                                                     })
                                                }
                                            });                            
                                        }
                                    }
                                }
                                else
                                {
                                    if (data && data.length > 0)
                                    {
                                        if(data[0].user_detail.length>0)
                                        {
                                            var min_parameter_value = 0;
                                            var temp = $filter('filter')(dialog.OnWorkInfo_detail, { user_no: data[0].user_detail[0].user_no }, true);
                                            if (temp && temp.length > 0) {
                                                if (temp[0].parameter_value >= data[0].user_detail[0].parameter_value) {
                                                    min_parameter_value = data[0].user_detail[0].parameter_value;
                                                }
                                                else {
                                                    min_parameter_value = temp[0].parameter_value;
                                                }
                                                dialog.OnWorkInfo_detail.forEach(function (detail) {
                                                    if (detail.user_no == temp[0].user_no) {
                                                        detail.parameter_value = min_parameter_value;
                                                    }
                                                })
                                            }
                                            else {
                                                var tmpUser = {
                                                    user_no: data[0].user_detail[0].user_no,
                                                    user_name: data[0].user_detail[0].user_name,
                                                    parameter_value: 0  //预设为0
                                                };
                                                dialog.OnWorkInfo_detail.push(tmpUser);
                                            }
                                        }
                                    }
                                  
                                }
                            },
                            back: function () {
                                this.hide();
                            },
                            changeParameter:function(){
                                $mdDialog.dialog(
                                     'module/moduleB/program/B02/B0235/CheckPermission_tmp.html',
                                     function (dialogcheck) {
                                         return {
                                             css_url: 'module/moduleB/program/B02/B0235/B0235.css',
                                             showPassword: function (id) {
                                                 if (document.getElementById(id).type == 'password') {
                                                     document.getElementById(id).type = 'text';
                                                     dialogcheck.groupuser_password_show = true;
                                                 } else {
                                                     document.getElementById(id).type = 'password';
                                                     dialogcheck.groupuser_password_show = false;
                                                 }
                                             },
                                             confirm: function () {
                                                 if (dialogcheck.Account && dialogcheck.Password) {
                                                     //检核权限
													 if(dialog.group_user_list.indexOf(dialogcheck.Account) > -1)
													 {
															$MMWService.sendToServer({
																uri : 'ServicesSTD.Module_SYS.user_permissions_info_get_json',
																content : {
																	login_employee_no:dialogcheck.Account,
																	login_employee_password:dialogcheck.Password
																},
																success : function(data){
																	 dialogcheck.hide();
																	 var xlist = document.getElementsByClassName("checktype");
																	 if (xlist && xlist.length > 0) {
																		 for (var i = 0; i < xlist.length; i++) {
																			 xlist[i].readOnly = false;
																		 }
																	 };
																},
																error:function(){
																	$rootScope.showAlert($filter('translate')('B0235.msg.password_error'), function () {
																	    document.getElementById('groupuser_password').focus();
																    });
																}
															});
															
													 }
                                                     else {
                                                         $rootScope.showAlert($filter('translate')('B0235.msg.no_permission'), function () {
                                                             document.getElementById('groupuser_account').focus();
                                                         });
                                                     }
                                                 }
                                             },
                                             back: function () {
                                                 dialogcheck.hide();
                                             }
                                         }
                                    })
                            },
                            confirm: function () {
								errormsg = "";   //清空报错信息
                                errormsgfinal = "";//清空报错信息
                                beforeEmpWorkSet(dialog, function () {
                                    empWorkSet(dialog);
                                });
                            }
                        };
                    }
                );
            };
        }]);
});
